import Vue from 'vue';
import VueRouter from 'vue-router';
import store from '../store'

Vue.use(VueRouter);

const router = new VueRouter({
    mode:'history',
    routes:[
        {
            path:'/',
            component:() => import('../views/Main.vue'),
            children:[
                {
                    path:'/',
                    component:() => import('../views/Home.vue')
                },
                {
                    path:'/home',
                    name:'Home',
                    component:() => import('../views/Home.vue')
                },
                {
                    path:'/goods',
                    name:'Goods',
                    component:()=>import('../views/Goods.vue')
                },
                {
                    path:'/order',
                    name:'Order',
                    component:()=>import('../views/Order.vue')
                },
            ]
        },{
            path:'/login',
            name:'Login',
            component:() => import('../views/Login.vue')
        }
    ],
})

//全局路由前置守卫，跳转链接之前调用
router.beforeEach((to,from,next)=>{
    //执行store中的getToken函数，获取token保存在state中
    store.commit('getToken');
    //获取保存在state中的token
    const token = store.state.login.token;
    //判断token是否存在
    if(!token && to.name !== 'Login'){
        //如果不存在，跳转到登录页
        next({name:'Login'});
    }else{
        //如果存在则进行正常页面跳转
        next()
    }
})

export default router;